package com.itstudio.portal.run;

import com.itstudio.portal.entity.News;
import com.itstudio.portal.entity.Project;
import com.itstudio.portal.service.NewsService;
import com.itstudio.portal.service.ProjectService;
import com.itstudio.portal.utils.Const;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ViewCountRunning implements CommandLineRunner {

    final ProjectService projectService;

    final
    RedisTemplate  redisTemplate;

    final NewsService  newsService;

    public ViewCountRunning(ProjectService projectService, RedisTemplate redisTemplate, final NewsService  newsService) {
        this.projectService = projectService;
        this.redisTemplate = redisTemplate;
        this.newsService = newsService;
    }

    @Override
    public void run(String... args) {
        List<Project> projects = projectService.list();
        List<News> newsList = newsService.list();
        Map<String, Integer> map = projects.stream()
                .collect(Collectors.toMap(project -> project.getId().toString(), project -> project.getVisitCount().intValue()));
        Map<String, Integer> newsMap = newsList.stream()
                .collect(Collectors.toMap(news -> news.getId().toString(), news -> news.getViewCount().intValue()));
        redisTemplate.opsForHash().putAll(Const.PROJECT_VIEW_COUNT_KEY, map);
        redisTemplate.opsForHash().putAll(Const.News_VIEW_COUNT_KEY, newsMap);
    }
}
